package com.honey.mybatis.generator.mappper;

import java.util.List;

import com.honey.compilation.xml.XmlElement;
import com.honey.core.dbmapping.introspect.IntrospectSchemaColumn;
import com.honey.core.dbmapping.introspect.IntrospectTableColumn;
import com.honey.core.dbmapping.structure.Column;
import com.honey.core.dbmapping.structure.Schema;
import com.honey.core.dbmapping.structure.Table;
import com.honey.core.dbmapping.structure.TableColumn;
import com.honey.mybatis.generator.MybatisPlugin;

public class InsertSelective extends AbstractMybatisMapper{

	public InsertSelective(MybatisPlugin belongPlugin) {
		super(belongPlugin);
	}

	public void appendElement(XmlElement parent, Schema schema, IntrospectSchemaColumn introspectSchemaColumn ){
		IntrospectTableColumn introspectTableColumn = null;
		if( schema instanceof Table ){
			introspectTableColumn = (IntrospectTableColumn)introspectSchemaColumn;
		}else{
			return ;
		}
		
		parent.addNewLine();
		parent.addComments(
				"插入不为空的记录,\"null\"值由数据库默认值填充,包含大字段."
		);
		XmlElement insert = new XmlElement(parent,"insert")
		.addAttribute("id",MapperConstant.INSERT_SELECTIVE_MAPPER_ID)
		.addAttribute("parameterType",super.getEntityPrimitiveClassType(schema).getLongName())
		.addAttribute("timeout", mybatisPlugin.getConnectionTimeOut())
		.addAttribute("flushCache", "true")
		.addAttribute("useGeneratedKeys", "true")
		.addTextElement("INSERT INTO " + schema.getName())
		;
		
		List<TableColumn> list = introspectTableColumn.primaryKeyColumns();
		String modelPackage = super.getModelPrimitiveClassType(schema).getLongName();
		StringBuilder sb = new StringBuilder();
		boolean comma = false;
		for(TableColumn column : list ){
			if(comma) sb.append(",");else comma = true;
			sb.append(column.getJavaProperty());
		}
		insert.addAttribute("keyProperty", sb.toString());
		sb.setLength(0);
		XmlElement colEle = new XmlElement("trim").addAttribute("prefix","(").addAttribute("suffix",")").addAttribute("suffixOverrides",",");
		XmlElement valuesEle = new XmlElement("trim").addAttribute("prefix","VALUES (").addAttribute("suffix",")").addAttribute("suffixOverrides",",");
		
		List<Column> columns = introspectTableColumn.allColumns();
		for(Column column : columns ){
			TableColumn tc =(TableColumn)column;
			if(tc.isPrimaryKey()) continue;
			String fieldName =super.getFieldName(column);
			colEle.addTextElement("<if test=\""+fieldName+" != null\" >"+column.getName()+",</if>");
			String typeHandler="";
			if( column.getEnumSchema() != null){
				typeHandler=",typeHandler=" + modelPackage ;
			}
			valuesEle.addTextElement("<if test=\""+fieldName+" != null\" >#{"+fieldName+",jdbcType="+JdbcTypeName.getJdbcTypeName(column.getJdbcType())+typeHandler+"},</if>");
		}
		insert.addElement(colEle);
		insert.addElement(valuesEle);
	}
}
